// 定义一个枚举来表示 JSON 值的不同类型
#[derive(Debug)]
enum JsonValue {
    Null,
    Boolean(bool),
    Number(f64),
    String(String),
    Array(Vec<JsonValue>),
    Object(Vec<(String, JsonValue)>),
}

// 为不同类型实现 From 特征转换为 JsonValue
impl From<()> for JsonValue {
    fn from(_: ()) -> Self {
        JsonValue::Null
    }
}

impl From<bool> for JsonValue {
    fn from(value: bool) -> Self {
        JsonValue::Boolean(value)
    }
}

impl From<f64> for JsonValue {
    fn from(value: f64) -> Self {
        JsonValue::Number(value)
    }
}

impl From<String> for JsonValue {
    fn from(value: String) -> Self {
        JsonValue::String(value)
    }
}

impl From<&str> for JsonValue {
    fn from(value: &str) -> Self {
        JsonValue::String(value.to_string())
    }
}

impl From<Vec<JsonValue>> for JsonValue {
    fn from(value: Vec<JsonValue>) -> Self {
        JsonValue::Array(value)
    }
}

impl From<Vec<(String, JsonValue)>> for JsonValue {
    fn from(value: Vec<(String, JsonValue)>) -> Self {
        JsonValue::Object(value)
    }
}

impl JsonValue {
    // 创建一个空的 Object 类型的 JsonValue
    pub fn new_object() -> Self {
        JsonValue::Object(Vec::new())
    }

    // 为 Object 类型的 JsonValue 添加键值对
    pub fn push_to_object(&mut self, key: String, value: JsonValue) {
        if let JsonValue::Object(ref mut obj) = self {
            obj.push((key, value));
        }
    }

    // 创建一个空的 Array 类型的 JsonValue
    pub fn new_array() -> Self {
        JsonValue::Array(Vec::new())
    }

    // 为 Array 类型的 JsonValue 添加元素
    pub fn push_to_array(&mut self, value: JsonValue) {
        if let JsonValue::Array(ref mut arr) = self {
            arr.push(value);
        }
    }

    // 解析字符串为 JsonValue
    pub fn parse(json_str: &str) -> Result<JsonValue, &'static str> {
        let mut chars = json_str.chars().peekable();
        Self::parse_value(&mut chars)
    }

    fn parse_value<I>(chars: &mut std::iter::Peekable<I>) -> Result<JsonValue, &'static str>
    where
        I: Iterator<Item = char>,
    {
        while let Some(&c) = chars.peek() {
            match c {
                ' ' | '\t' | '\n' | '\r' => {
                    chars.next();
                    continue;
                }
                '{' => return Self::parse_object(chars),
                '[' => return Self::parse_array(chars),
                '"' => return Self::parse_string(chars),
                't' => {
                    if chars.by_ref().take(4).collect::<String>() == "true" {
                        return Ok(JsonValue::Boolean(true));
                    }
                }
                'f' => {
                    if chars.by_ref().take(5).collect::<String>() == "false" {
                        return Ok(JsonValue::Boolean(false));
                    }
                }
                'n' => {
                    if chars.by_ref().take(4).collect::<String>() == "null" {
                        return Ok(JsonValue::Null);
                    }
                }
                '-' | '0'..='9' => return Self::parse_number(chars),
                _ => return Err("Invalid JSON"),
            }
        }
        Err("Invalid JSON")
    }

    fn parse_object<I>(chars: &mut std::iter::Peekable<I>) -> Result<JsonValue, &'static str>
    where
        I: Iterator<Item = char>,
    {
        chars.next(); // 跳过 '{'
        let mut obj = Vec::new();
        loop {
            while let Some(&c) = chars.peek() {
                match c {
                    ' ' | '\t' | '\n' | '\r' => {
                        chars.next();
                        continue;
                    }
                    '"' => {
                        let key = Self::parse_string(chars)?;
                        if let JsonValue::String(key_str) = key {
                            while let Some(&c) = chars.peek() {
                                match c {
                                    ' ' | '\t' | '\n' | '\r' => {
                                        chars.next();
                                        continue;
                                    }
                                    ':' => {
                                        chars.next();
                                        let value = Self::parse_value(chars)?;
                                        obj.push((key_str, value));
                                        break;
                                    }
                                    _ => return Err("Invalid JSON"),
                                }
                            }
                        } else {
                            return Err("Invalid JSON");
                        }
                    }
                    '}' => {
                        chars.next();
                        return Ok(JsonValue::Object(obj));
                    }
                    ',' => {
                        chars.next();
                        break;
                    }
                    _ => return Err("Invalid JSON"),
                }
            }
        }
    }

    fn parse_array<I>(chars: &mut std::iter::Peekable<I>) -> Result<JsonValue, &'static str>
    where
        I: Iterator<Item = char>,
    {
        chars.next(); // 跳过 '['
        let mut arr = Vec::new();
        loop {
            while let Some(&c) = chars.peek() {
                match c {
                    ' ' | '\t' | '\n' | '\r' => {
                        chars.next();
                        continue;
                    }
                    ']' => {
                        chars.next();
                        return Ok(JsonValue::Array(arr));
                    }
                    ',' => {
                        chars.next();
                        continue;
                    }
                    _ => {
                        let value = Self::parse_value(chars)?;
                        arr.push(value);
                    }
                }
            }
        }
    }

    fn parse_string<I>(chars: &mut std::iter::Peekable<I>) -> Result<JsonValue, &'static str>
    where
        I: Iterator<Item = char>,
    {
        chars.next(); // 跳过 '"'
        let mut s = String::new();
        while let Some(c) = chars.next() {
            if c == '"' {
                return Ok(JsonValue::String(s));
            }
            s.push(c);
        }
        Err("Invalid JSON")
    }

    fn parse_number<I>(chars: &mut std::iter::Peekable<I>) -> Result<JsonValue, &'static str>
    where
        I: Iterator<Item = char>,
    {
        let mut num_str = String::new();
        while let Some(&c) = chars.peek() {
            match c {
                '-' | '0'..='9' | '.' | 'e' | 'E' => {
                    num_str.push(c);
                    chars.next();
                }
                _ => break,
            }
        }
        if let Ok(num) = num_str.parse::<f64>() {
            Ok(JsonValue::Number(num))
        } else {
            Err("Invalid JSON")
        }
    }

    // 将 JsonValue 转换为字符串
    pub fn stringify(&self) -> String {
        match self {
            JsonValue::Null => "null".to_string(),
            JsonValue::Boolean(b) => b.to_string(),
            JsonValue::Number(n) => n.to_string(),
            JsonValue::String(s) => format!("\"{}\"", s),
            JsonValue::Array(arr) => {
                let elements: Vec<String> = arr.iter().map(|v| v.stringify()).collect();
                format!("[{}]", elements.join(","))
            }
            JsonValue::Object(obj) => {
                let pairs: Vec<String> = obj
                   .iter()
                   .map(|(k, v)| format!("\"{}\":{}", k, v.stringify()))
                   .collect();
                format!("{{{}}}", pairs.join(","))
            }
        }
    }
}

// 定义一个函数来创建一个简单的 JSON 对象示例
fn create_json_object() -> JsonValue {
    let mut person = JsonValue::new_object();
    person.push_to_object("name".to_string(), "Alice".into());
    person.push_to_object("age".to_string(), 30.0.into());
    person.push_to_object("is_student".to_string(), false.into());

    let mut hobbies = JsonValue::new_array();
    hobbies.push_to_array("reading".into());
    hobbies.push_to_array("swimming".into());
    person.push_to_object("hobbies".to_string(), hobbies);

    person
}

fn main() {
    let json = create_json_object();
    let json_str = json.stringify();
    println!("Stringified JSON: {}", json_str);

    if let Ok(parsed_json) = JsonValue::parse(&json_str) {
        println!("Parsed JSON: {:?}", parsed_json);
    } else {
        println!("Failed to parse JSON");
    }
}    

#[cfg(test)]
mod test {
    use super::*;

    // 测试 From 特征转换
    #[test]
    fn test_from_conversions() {
        assert_eq!(JsonValue::from(true), JsonValue::Boolean(true));
        assert_eq!(JsonValue::from(123.45f64), JsonValue::Number(123.45));
        assert_eq!(JsonValue::from("test".to_string()), JsonValue::String("test".to_string()));
        assert_eq!(JsonValue::from("hello"), JsonValue::String("hello".to_string()));
        assert_eq!(JsonValue::from(()), JsonValue::Null);
    }

    // 测试 Object 构造函数和 push 方法
    #[test]
    fn test_object_construction() {
        let mut obj = JsonValue::new_object();
        obj.push_to_object("name".to_string(), "Alice".into());
        obj.push_to_object("age".to_string(), 30.into());
        
        if let JsonValue::Object(ref entries) = obj {
            assert_eq!(entries.len(), 2);
            assert!(entries.iter().any(|(k, v)| *k == "name" && matches!(v, JsonValue::String(s) if s == "Alice")));
            assert!(entries.iter().any(|(k, v)| *k == "age" && matches!(v, JsonValue::Number(n) if *n == 30.0)));
        } else {
            panic!("Expected Object variant");
        }
    }

    // 测试 Array 构造函数和 push 方法
    #[test]
    fn test_array_construction() {
        let mut arr = JsonValue::new_array();
        arr.push_to_array("apple".into());
        arr.push_to_array(JsonValue::Boolean(false));
        
        if let JsonValue::Array(ref elements) = arr {
            assert_eq!(elements.len(), 2);
            assert!(elements[0] == JsonValue::String("apple".to_string()));
            assert!(elements[1] == JsonValue::Boolean(false));
        } else {
            panic!("Expected Array variant");
        }
    }

    // 测试 JSON 解析（parse）
    #[test]
    fn test_json_parse() {
        // 测试 Null
        assert_eq!(JsonValue::parse("null").unwrap(), JsonValue::Null);
        
        // 测试 Boolean
        assert_eq!(JsonValue::parse("true").unwrap(), JsonValue::Boolean(true));
        assert_eq!(JsonValue::parse("false").unwrap(), JsonValue::Boolean(false));
        
        // 测试 Number
        assert_eq!(JsonValue::parse("42").unwrap(), JsonValue::Number(42.0));
        assert_eq!(JsonValue::parse("3.14").unwrap(), JsonValue::Number(3.14));
        assert_eq!(JsonValue::parse("-123.45e6").unwrap(), JsonValue::Number(-123450000.0));
        
        // 测试 String
        assert_eq!(JsonValue::parse("\"hello\"").unwrap(), JsonValue::String("hello".to_string()));
        assert_eq!(JsonValue::parse("\"\\\"escaped\\\"\"").unwrap(), JsonValue::String("\"escaped\"".to_string()));
        
        // 测试 Array
        let arr = JsonValue::parse("[1, true, null, \"test\"]").unwrap();
        if let JsonValue::Array(elements) = arr {
            assert_eq!(elements.len(), 4);
            assert!(matches!(elements[0], JsonValue::Number(1.0)));
            assert!(elements[1] == JsonValue::Boolean(true));
            assert!(elements[2] == JsonValue::Null);
            assert!(elements[3] == JsonValue::String("test".to_string()));
        } else {
            panic!("Expected Array variant");
        }
        
        // 测试 Object
        let obj = JsonValue::parse(r#"{"name":"Bob", "age":35, "is_student":false}"#).unwrap();
        if let JsonValue::Object(entries) = obj {
            assert_eq!(entries.len(), 3);
            assert!(entries.iter().any(|(k, v)| *k == "name" && matches!(v, JsonValue::String(s) if s == "Bob")));
            assert!(entries.iter().any(|(k, v)| *k == "age" && matches!(v, JsonValue::Number(n) if *n == 35.0)));
            assert!(entries.iter().any(|(k, v)| *k == "is_student" && matches!(v, JsonValue::Boolean(b) if !b)));
        } else {
            panic!("Expected Object variant");
        }
        
        // 测试带空格的 JSON
        let spaced_json = r#"
        {
            "key": [1, 2, 3],
            "nested": { "a": true }
        }
        "#;
        let parsed = JsonValue::parse(spaced_json).unwrap();
        assert!(matches!(parsed, JsonValue::Object(_)));
    }

    // 测试 JSON 序列化（stringify）
    #[test]
    fn test_json_stringify() {
        // 测试 Null
        assert_eq!(JsonValue::Null.stringify(), "null");
        
        // 测试 Boolean
        assert_eq!(JsonValue::Boolean(true).stringify(), "true");
        assert_eq!(JsonValue::Boolean(false).stringify(), "false");
        
        // 测试 Number
        assert_eq!(JsonValue::Number(42.0).stringify(), "42");
        assert_eq!(JsonValue::Number(3.14).stringify(), "3.14");
        assert_eq!(JsonValue::Number(-123.45).stringify(), "-123.45");
        
        // 测试 String
        assert_eq!(JsonValue::String("hello".to_string()).stringify(), "\"hello\"");
        assert_eq!(JsonValue::String("\"escaped\"".to_string()).stringify(), "\"\\\"escaped\\\"\"");
        
        // 测试 Array
        let arr = JsonValue::Array(vec![
            JsonValue::Number(1),
            JsonValue::Boolean(false),
            JsonValue::String("test".to_string()),
        ]);
        assert_eq!(arr.stringify(), "[1,false,\"test\"]");
        
        // 测试 Object
        let obj = JsonValue::Object(vec![
            ("name".to_string(), JsonValue::String("Alice".to_string())),
            ("age".to_string(), JsonValue::Number(30.0)),
        ]);
        assert_eq!(obj.stringify(), r#"{"name":"Alice","age":30}"#);
        
        // 测试嵌套结构
        let nested = JsonValue::Object(vec![
            ("array".to_string(), JsonValue::Array(vec![JsonValue::Null, JsonValue::Number(0)])),
            ("object".to_string(), JsonValue::Object(vec![("key".to_string(), JsonValue::String("value".to_string()))])),
        ]);
        assert_eq!(nested.stringify(), r#"{"array":[null,0],"object":{"key":"value"}}"#);
    }

    // 测试解析错误情况
    #[test]
    fn test_parse_errors() {
        assert!(JsonValue::parse("abc").is_err());
        assert!(JsonValue::parse("[1, 2, ").is_err());
        assert!(JsonValue::parse("{key: \"value\"}").is_err()); // 缺少引号
        assert!(JsonValue::parse("true true").is_err()); // 多余字符
    }
}